package dal.project_team;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;

import dal.database.DBUtil;

public class ProjectTeamUtil {
	
	
	public String getId() {
		String Team_id="";
		String qry="select Team_id from project_teams";
		ResultSet rs=null;
		ArrayList<Integer> al=new ArrayList<Integer>();
		int idIntLength=5;
		try {
			
			rs=DBUtil.getCon().createStatement().executeQuery(qry);
			if(rs.next()){
				
				String tempId=rs.getString(1);
				String strIntId=tempId.substring(3, (tempId.length()));
				System.out.println("strIntId = "+strIntId);
				
				al.add(Integer.parseInt(strIntId));
				while(rs.next()){
					tempId=rs.getString(1);
					strIntId=tempId.substring(3, (tempId.length()));
					al.add(Integer.parseInt(strIntId));
				}
				
				Collections.sort(al);
				
				System.out.println("size  = "+al.size());
				
				Integer intId=al.get((al.size()-1));
				intId++;
				strIntId=intId.toString();
				System.out.println("strIntId = "+strIntId);
				int fillerLength=idIntLength-(strIntId.length());
				System.out.println("filler lnght  =  "+fillerLength);
				
				int i=0;
				String zeroString="";
				while(i<fillerLength){
					zeroString=zeroString+"0";
					i++;
				}
				
				Team_id="TM"+zeroString+strIntId;
				
			}else{
				
				Team_id="TM00001";
			}
			
			rs.close();
			
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
		return Team_id;
	}
	
	public boolean add(Object instance){
		
		boolean isOk=false;
		ProjectTeam projectTeam=(ProjectTeam)instance;
		
		String qry="insert into project_teams values(?,?,?,?)";
		System.out.println(qry);
		
		try {
			
			PreparedStatement preparedStatement=DBUtil.getCon().prepareStatement(qry);
			
			preparedStatement.setString(1, projectTeam.Team_id);
			preparedStatement.setString(2, projectTeam.Team_name);
			preparedStatement.setString(3, projectTeam.Project_id);
			preparedStatement.setString(4, projectTeam.Project_name);
			
			System.out.println(projectTeam.Team_id+""+projectTeam.Team_name+""+projectTeam.Project_id+""+projectTeam.Project_name);
			
			int res=preparedStatement.executeUpdate();
			
			if(res>0){
				isOk=true;
			}
			else{
				isOk=false;
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			// TODO: handle exception
		}
		
		return isOk;
		
		
	}

}
